package com.su.gulimall.seckill.controller;

import com.su.common.utils.R;
import com.su.gulimall.seckill.service.SecKillService;
import com.su.gulimall.seckill.to.SecKillSkuRedisTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class SecKillController {
    @Autowired
    SecKillService secKillService;

    @GetMapping("/getCurrentSecKillSkus")
    @ResponseBody
    public R getCurrentSecKillSkus() {
        List<SecKillSkuRedisTo> vos = secKillService.getCurrentSecKillSkus();
        return R.ok().setData(vos);
    }

    @GetMapping("/sku/seckill/{skuId}")
    @ResponseBody
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        SecKillSkuRedisTo redisTo = secKillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(redisTo);
    }

    @GetMapping("/kill")
    public String kill(@RequestParam("killId") String killId,
                       @RequestParam("key") String key,
                       @RequestParam("num") Integer num,
                       Model model) {
        //流程二优势，快，不访问数据库；流程2缺点：订单服务宕机，缺少消费者，导致流程无法正常进行
        //1.使用拦截器对用户登录状态进行判断
        //只有登录以后才可以进行秒杀
        //2.秒杀请求的合法性
        //3.获取信号量
        //秒杀活动的商品数量是提前在redis中放置的（此时已经对库存系统进行了相关的锁定）
        //商品的数量对应了redis中该商品的信号量
        //4.秒杀成功：将用户，订单号，商品信息发送给MQ,(流量消峰)
        String orderSn = secKillService.kill(killId, key, num);
        model.addAttribute("orderSn", orderSn);
        return "success";

}
}
